package com.lykj.llw.box.ui.activity.agent

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ClipboardUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.dinuscxj.itemdecoration.LinearDividerItemDecoration
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.ChooseGameAdapter
import com.lykj.llw.box.adapter.ChooseServerAdapter
import com.lykj.llw.box.data.bean.response.ChooseGameResponse
import com.lykj.llw.box.data.bean.response.agent.AgentShareResponse
import com.lykj.llw.box.databinding.ActAgentInviteBinding
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 代理-邀请
 * ================================================
 *
 * @author gosha
 * @date 2023/10/30-17:55
 */
class AgentInviteActivity : BaseActivity() {
    lateinit var binding: ActAgentInviteBinding

    private var mTextWatcher: TextWatcher? = null
    private val mAdapter = ChooseGameAdapter()
    private val mData = ArrayList<ChooseGameResponse.DataDTO>()
    private var mSelectGameId = -1

    //    private var mIsShow = false
    private var mIsSet = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActAgentInviteBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar.with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "邀请"
        binding.titleBar.tvRightOption.visibility = View.GONE

        initRCV()
    }

    private fun initRCV() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvChoose.layoutManager = linearLayoutManager
        binding.rcvChoose.setHasFixedSize(true)

        val dividerItemDecoration = LinearDividerItemDecoration(
            this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_5dp, resources.newTheme()
            )
        )
        binding.rcvChoose.addItemDecoration(dividerItemDecoration, 0)
        mAdapter.data = mData
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mSelectGameId = mData[position].id

            mIsSet = true
            //隐藏列表
            binding.etChooseGame.setText("${mData[position].name}")
            binding.rcvChoose.visibility = View.GONE
            binding.ivChoose.setImageResource(R.mipmap.ic_pull_down)


            obtainShareLink(mData[position].id, false)
        }
        binding.rcvChoose.adapter = mAdapter
    }

    //获取下拉游戏
    private fun obtainChooseGame(name: String) {
        RetrofitManager.instance.obtainChooseGame(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@AgentInviteActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(
                    responseBody, ChooseGameResponse::class.java
                )

                mData.clear()
                if (bean.data.size > 0) {
                    binding.rcvChoose.visibility = View.VISIBLE
                    mData.addAll(bean.data)

                    binding.ivChoose.setImageResource(R.mipmap.ic_pull_up)
                } else {
                    binding.rcvChoose.visibility = View.GONE
                    binding.ivChoose.setImageResource(R.mipmap.ic_pull_down)
                    ToastUtils.showShort(this@AgentInviteActivity, "没有搜索到该游戏信息")
                }

                mAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@AgentInviteActivity, msg)
                }
            }
        }, name)
    }

    //分享链接
    private fun obtainShareLink(id: Int, isBox: Boolean) {
        RetrofitManager.instance.obtainShareLink("$id", object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, AgentShareResponse::class.java)

                if (isBox) {
                    binding.tvBoxInviteUrl.text = "${bean.data}"
                    binding.tvBoxInviteUrl.setTextColor(ColorUtils.getColor(R.color.black_FF242424))
                } else {
                    binding.tvGameInviteUrl.text = "${bean.data}"
                    binding.tvGameInviteUrl.setTextColor(ColorUtils.getColor(R.color.black_FF242424))
                }
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@AgentInviteActivity, it)
                }
            }
        })
    }

    override fun initData() {
        obtainShareLink(1, true)
//        obtainChooseGame("")
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        mTextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (!mIsSet) {
                    obtainChooseGame(binding.etChooseGame.text.toString())
                } else {
                    mIsSet = false
                }
            }
        }
        binding.etChooseGame.addTextChangedListener(mTextWatcher)

        binding.ivDelete.clickWithTrigger(250) {
            KeyboardUtils.hideSoftInput(this)
            binding.etChooseGame.setText("")
        }

        binding.root.clickWithTrigger(100) {
//            mIsSet = false
            //隐藏列表
            binding.rcvChoose.visibility = View.GONE
            binding.ivChoose.setImageResource(R.mipmap.ic_pull_down)
        }

        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (it == 0) {
                binding.etChooseGame.clearFocus()
            }
        }

        binding.tvBtnCopyBoxInviteUrl.clickWithTrigger(350) {
            ClipboardUtils.copyText(binding.tvBoxInviteUrl.text)
            ToastUtils.showShort(this, "复制盒子链接成功")
        }

        binding.tvBtnCopyGameInviteUrl.clickWithTrigger(350) {
            if (binding.tvGameInviteUrl.text == "暂无生成") {
                ToastUtils.showLong(this, "请先选择游戏,获取游戏链接")
                return@clickWithTrigger
            }
            ClipboardUtils.copyText(binding.tvGameInviteUrl.text)
            ToastUtils.showShort(this, "复制游戏链接成功")
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}